<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惠农通 - 农场管理</title>
    <link rel="icon" href="./assets/logo.ico" type="images/x-ico" />
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/dashboard.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://webapi.amap.com/maps?v=2.0&key=594a5e45ffcba6b8cf6afa7b1c7c50a2"></script>
    <script src="https://webapi.amap.com/ui/1.1/main.js"></script>
    <style>

        /* 地图样式 */
        .farm-map {
            height: 150px;
            width: 100%;
            border-radius: 8px;
            margin-bottom: 1rem;
            overflow: hidden;
            position: relative;
            cursor: pointer;
            background: #f5f5f5;
        }
        
        /* 全屏地图模态框样式 */
        #fullMapModal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .full-map-container {
            width: 80%;
            height: 80%;
            background: white;
            border-radius: 8px;
            padding: 1rem;
            position: relative;
        }
        
        #fullMap {
            width: 100%;
            height: 100%;
        }
        
        .close-full-map {
            position: absolute;
            top: 10px;
            right: 10px;
            background: var(--danger-color);
            color: white;
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            font-size: 1rem;
            cursor: pointer;
            z-index: 1001;
        }


        /* 农场管理特定样式 */
        .farm-card {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 1.5rem;
            transition: all 0.3s;
            border-left: 4px solid var(--primary-color);
            position: relative;
            overflow: hidden;
        }
        
        .farm-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .farm-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }
        
        .farm-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 0.5rem;
        }
        
        .farm-status {
            position: absolute;
            top: 15px;
            right: 15px;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .status-active {
            background-color: rgba(76, 175, 80, 0.1);
            color: var(--primary-color);
        }
        
        .status-inactive {
            background-color: rgba(244, 67, 54, 0.1);
            color: var(--danger-color);
        }
        
        .farm-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--text-light);
            font-size: 0.9rem;
        }
        
        .meta-item i {
            color: var(--primary-color);
        }
        
        .farm-actions {
            display: flex;
            gap: 0.5rem;
            justify-content: flex-end;
        }
        
        /* 地图缩略图样式 */
        .farm-map {
            height: 150px;
            background-color: #f5f5f5;
            border-radius: 8px;
            margin-bottom: 1rem;
            overflow: hidden;
            position: relative;
        }
        
        .farm-map img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s;
        }
        
        .farm-card:hover .farm-map img {
            transform: scale(1.05);
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .farm-header {
                flex-direction: column;
            }
            
            .farm-actions {
                justify-content: flex-start;
                margin-top: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏 -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <img src="assets/logo.png" alt="惠农通">
                    <h2>惠农通</h2>
                </div>
            </div>
            <nav class="sidebar-menu">
                <ul>
                    <li data-page="dashboard">
                        <i class="fas fa-chart-line"></i>
                        <span>数据概览</span>
                    </li>
                    <li data-page="employees">
                        <i class="fas fa-users"></i>
                        <span>员工管理</span>
                    </li>
                    <li data-page="expert">
                        <i class="fas fa-user-tie"></i>
                        <span>专家管理</span>
                    </li>
                    <li class="active" data-page="farm-management">
                        <i class="fas fa-warehouse"></i>
                        <span>农场管理</span>
                    </li>
                    <li data-page="product">
                        <i class="fas fa-box-open"></i>
                        <span>产品管理</span>
                    </li>
                    <li data-page="order">
                        <i class="fas fa-shopping-cart"></i>
                        <span>订单管理</span>
                    </li>
                    <li data-page="ai-chat">
                        <i class="fas fa-robot"></i>
                        <span>AI问答</span>
                    </li>
                    <li data-page="activities">
                        <i class="fas fa-tractor"></i>
                        <span>农业活动</span>
                    </li>
                    <li data-page="settings">
                        <i class="fas fa-cog"></i>
                        <span>系统设置</span>
                    </li>
                </ul>
            </nav>
            <div class="sidebar-footer">
                <button class="logout-btn" id="logoutBtn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>退出登录</span>
                </button>
            </div>
        </aside>

        <!-- 主内容区 -->
        <main class="main-content">
            <header class="main-header">
                <h1 id="pageTitle">农场管理</h1>
                <div class="user-info">
                    <span class="welcome">欢迎，<span id="currentUser">管理员</span></span>
                    <div class="avatar">
                        <i class="fas fa-user-circle"></i>
                    </div>
                </div>
            </header>

            <!-- 农场管理内容 -->
            <div class="page-content farm-management">
                <div class="dashboard-controls">
                    <div class="search-box">
                        <i class="fas fa-search"></i>
                        <input type="text" id="searchFarm" placeholder="输入农场名称搜索">
                        <button class="search-btn" id="searchFarmBtn">搜索</button>
                    </div>
                    <button class="primary-btn" id="addFarmBtn">
                        <i class="fas fa-plus"></i> 新增农场
                    </button>
                </div>

                <div id="farmList">
                    <!-- 农场列表将通过JavaScript动态加载 -->
                    <div class="loading-spinner">
                        <i class="fas fa-spinner fa-spin"></i> 加载中...
                    </div>
                </div>

                <div class="pagination-wrapper">
                    <div class="pagination-controls">
                        <button class="page-btn" id="prevFarmPageBtn">
                            <i class="fas fa-chevron-left"></i> 上一页
                        </button>
                        <span class="page-info" id="currentFarmPage">第 1 页</span>
                        <button class="page-btn" id="nextFarmPageBtn">
                            下一页 <i class="fas fa-chevron-right"></i>
                        </button>
                        <select class="page-select" id="farmPageSize">
                            <option value="10">每页10条</option>
                            <option value="20">每页20条</option>
                            <option value="50">每页50条</option>
                        </select>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 农场表单模态框 -->
    <div id="farmModal" class="modal">
        <div class="modal-dialog">
            <div class="modal-header">
                <h3 id="modalTitle">新增农场</h3>
                <button class="close-btn" id="closeModalBtn">&times;</button>
            </div>
            <form id="farmForm" class="modal-body">
                <input type="hidden" id="farmId">
                <div class="form-group">
                    <label for="farmName">农场名称</label>
                    <input type="text" id="farmName" placeholder="输入农场名称" required>
                </div>
                <div class="form-group">
                    <label for="farmLocation">农场位置</label>
                    <input type="text" id="farmLocation" placeholder="输入农场详细地址" required>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="farmArea">农场面积(亩)</label>
                        <input type="number" id="farmArea" placeholder="输入农场面积" step="0.01" min="0" required>
                    </div>
                    <div class="form-group">
                        <label for="farmDate">建立日期</label>
                        <input type="date" id="farmDate" required>
                    </div>
                </div>
                <div class="form-group">
                    <label for="farmManager">负责人</label>
                    <select id="farmManager" required>
                        <option value="">选择负责人</option>
                        <!-- 负责人选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="farmStatus">农场状态</label>
                    <select id="farmStatus" required>
                        <option value="1">启用</option>
                        <option value="0">停用</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="farmDescription">农场描述</label>
                    <textarea id="farmDescription" placeholder="输入农场描述信息" rows="3"></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="secondary-btn" id="cancelModalBtn">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="submit" class="primary-btn">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script src="js/common.js"></script>
    <script>
        // 基础URL配置
        const BASE_URL = 'http://192.168.8.128:8080';
        const API_BASE_URL = `${BASE_URL}/admin/farm`;
        
        document.addEventListener('DOMContentLoaded', function() {
            // 全局变量
            let currentFarmPage = 1;
            let pageSize = 10;
            let searchKeyword = '';
            const token = localStorage.getItem('token');
            // 全局地图变量
            let farmMarkers = [];
            let currentFullMap = null;
            
            // DOM元素
            const farmList = document.getElementById('farmList');
            const loadingSpinner = document.querySelector('.loading-spinner');
            const prevPageBtn = document.getElementById('prevFarmPageBtn');
            const nextPageBtn = document.getElementById('nextFarmPageBtn');
            const currentPageSpan = document.getElementById('currentFarmPage');
            const pageSizeSelect = document.getElementById('farmPageSize');
            const searchInput = document.getElementById('searchFarm');
            const searchBtn = document.getElementById('searchFarmBtn');
            const addFarmBtn = document.getElementById('addFarmBtn');
            const farmModal = document.getElementById('farmModal');
            const closeModalBtn = document.getElementById('closeModalBtn');
            const cancelModalBtn = document.getElementById('cancelModalBtn');
            const farmForm = document.getElementById('farmForm');
            const modalTitle = document.getElementById('modalTitle');
            
            // 侧边栏菜单项
            const menuItems = document.querySelectorAll('.sidebar-menu li');
            
            // 当前登录用户
            const currentUser = JSON.parse(localStorage.getItem('user')) || { name: '管理员' };
            document.getElementById('currentUser').textContent = currentUser.name;
            
            // 初始化页面
            initPage();
            
            // 事件监听
            prevPageBtn.addEventListener('click', goToPrevPage);
            nextPageBtn.addEventListener('click', goToNextPage);
            pageSizeSelect.addEventListener('change', changePageSize);
            searchBtn.addEventListener('click', performSearch);
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSearch();
                }
            });
            addFarmBtn.addEventListener('click', showAddFarmModal);
            closeModalBtn.addEventListener('click', hideFarmModal);
            cancelModalBtn.addEventListener('click', hideFarmModal);
            farmForm.addEventListener('submit', handleFarmSubmit);
            
            // 侧边栏菜单点击事件
            menuItems.forEach(item => {
                item.addEventListener('click', function() {
                    const page = this.getAttribute('data-page');
                    navigateToPage(page);
                });
            });
            
            // 页面导航函数
            function navigateToPage(page) {
                if (page === 'dashboard') {
                    window.location.href = 'dashboard.html';
                } else if (page === 'employees') {
                    window.location.href = 'employees.html';
                } else if (page === 'expert') {
                    window.location.href = 'expert.html';
                } else if (page === 'farm-management') {
                    window.location.href = 'farm.html';
                } else if (page === 'product') {
                    window.location.href = 'product.html';
                } else if (page === 'order') {
                    window.location.href = 'order.html';
                } else if (page === 'ai-chat') {
                    window.location.href = 'ai-chat.html';
                } else if (page === 'activities') {
                    window.location.href = 'activities.html';
                } else if (page === 'settings') {
                    window.location.href = 'settings.html';
                }
            }
            
            // 初始化页面
            function initPage() {
                setActiveMenuItem();
                loadFarms();
                loadManagers();


                document.getElementById('closeFullMapBtn').addEventListener('click', function() {
                document.getElementById('fullMapModal').style.display = 'none';
                if (currentFullMap) {
                currentFullMap.destroy();
                currentFullMap = null;
        }
    });
            }
            
            // 加载农场列表
            function loadFarms() {
                showLoading();
                
                // 构建查询参数
                const params = {
                    page: currentFarmPage,
                    pageSize: pageSize,
                    name: searchKeyword
                };
                
                fetch(`${API_BASE_URL}/page?${new URLSearchParams(params)}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log('农场数据:', data);
                        if (data.code === 1) {
                            renderFarms(data.data);
                            updatePaginationInfo();
                        } else {
                            alert('加载农场数据失败: ' + data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('加载农场数据时出错');
                    })
                    .finally(() => {
                        hideLoading();
                    });
            }
            
// 修改后的renderFarms函数
function renderFarms(pageResult) {
    // 清空现有内容
    farmList.innerHTML = '';
    
    // 检查数据是否有效
    if (!pageResult || !Array.isArray(pageResult.records)) {
        farmList.innerHTML = '<div class="no-data">无效的数据格式</div>';
        return;
    }
    
    if (pageResult.records.length === 0) {
        farmList.innerHTML = '<div class="no-data">没有找到匹配的农场</div>';
        return;
    }
    
    // 创建文档片段提高性能
    const fragment = document.createDocumentFragment();
    
    // 遍历所有农场记录
    pageResult.records.forEach(farm => {
        const farmCard = document.createElement('div');
        farmCard.className = 'farm-card';
        
        // 生成唯一ID用于地图容器
        const mapId = 'farm-map-' + farm.id;
        
        farmCard.innerHTML = `
            <div class="farm-header">
                <div>
                    <h3 class="farm-title">${farm.name || '未命名农场'}</h3>
                    <div class="farm-meta">
                        <div class="meta-item">
                            <i class="fas fa-map-marker-alt"></i>
                            <span>${farm.location || '位置未指定'}</span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-ruler-combined"></i>
                            <span>${farm.area || '0'} 亩</span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-calendar-alt"></i>
                            <span>${farm.establish_date || '日期未指定'}</span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-user-tie"></i>
                            <span>${farm.manager_name || '未指定'}</span>
                        </div>
                    </div>
                </div>
                <span class="farm-status ${farm.status == 1 ? 'status-active' : 'status-inactive'}">
                    ${farm.status == 1 ? '启用中' : '已停用'}
                </span>
            </div>
            <div class="farm-map" id="${mapId}">
                <div class="map-placeholder">地图加载中...</div>
            </div>
            <p class="farm-description">${farm.description || '暂无描述信息'}</p>
            <div class="farm-actions">
                <button class="secondary-btn btn-edit" data-id="${farm.id}">
                    <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="danger-btn btn-delete" data-id="${farm.id}">
                    <i class="fas fa-trash-alt"></i> 删除
                </button>
            </div>
        `;
        
        fragment.appendChild(farmCard);
    });
    
    // 一次性添加到DOM
    farmList.appendChild(fragment);
    
    // 延迟初始化地图，避免阻塞UI渲染
    setTimeout(() => {
        pageResult.records.forEach(farm => {
            const mapId = 'farm-map-' + farm.id;
            initMiniMap(mapId, farm);
            
            // 添加点击事件
            document.getElementById(mapId).addEventListener('click', () => {
                showFullMap(farm);
            });
        });
    }, 100);
    
    // 添加编辑和删除按钮事件
    addFarmActionListeners();
}


function addFarmActionListeners() {
    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', function() {
            const farmId = this.getAttribute('data-id');
            showEditFarmModal(farmId);
        });
    });
    
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            const farmId = this.getAttribute('data-id');
            confirmDeleteFarm(farmId);
        });
    });
}

// 更新分页信息
function updatePaginationInfo(totalItems) {
    const totalPages = Math.ceil(totalItems / pageSize);
    currentPageSpan.textContent = `第 ${currentFarmPage} 页 / 共 ${totalPages} 页`;
    
    // 禁用/启用上一页/下一页按钮
    prevPageBtn.disabled = currentFarmPage <= 1;
    nextPageBtn.disabled = currentFarmPage >= totalPages;
}
            // 更新分页信息
            function updatePaginationInfo() {
                currentPageSpan.textContent = `第 ${currentFarmPage} 页`;
                
                // 禁用/启用上一页/下一页按钮
                prevPageBtn.disabled = currentFarmPage <= 1;
                nextPageBtn.disabled = false; // 这里需要根据实际数据调整
            }
            
            // 上一页
            function goToPrevPage() {
                if (currentFarmPage > 1) {
                    currentFarmPage--;
                    loadFarms();
                }
            }
            
            // 下一页
            function goToNextPage() {
                currentFarmPage++;
                loadFarms();
            }
            
            // 改变每页显示数量
            function changePageSize() {
                pageSize = parseInt(pageSizeSelect.value);
                currentFarmPage = 1;
                loadFarms();
            }
            
            // 执行搜索
            function performSearch() {
                searchKeyword = searchInput.value.trim();
                currentFarmPage = 1;
                loadFarms();
            }
            
            // 显示加载中
            function showLoading() {
                loadingSpinner.style.display = 'block';
            }
            
            // 隐藏加载中
            function hideLoading() {
                loadingSpinner.style.display = 'none';
            }
            
            // 显示新增农场模态框
            function showAddFarmModal() {
                modalTitle.textContent = '新增农场';
                farmForm.reset();
                document.getElementById('farmId').value = '';
                document.getElementById('farmStatus').value = '1';
                farmModal.style.display = 'flex';
            }



            function initMiniMap(containerId, farm) {
    try {
        const map = new AMap.Map(containerId, {
            zoom: 12,
            viewMode: '2D',
            showIndoorMap: false,
            zoomEnable: false,
            dragEnable: false,
            animateEnable: false,
            keyboardEnable: false
        });
        
        // 清除占位元素
        const container = document.getElementById(containerId);
        const placeholder = container.querySelector('.map-placeholder');
        if (placeholder) {
            container.removeChild(placeholder);
        }
        
        // 地理编码或使用已有坐标
        if (farm.longitude && farm.latitude) {
            const lnglat = new AMap.LngLat(parseFloat(farm.longitude), parseFloat(farm.latitude));
            map.setCenter(lnglat);
            new AMap.Marker({
                position: lnglat,
                map: map,
                content: '<div class="mini-marker"></div>'
            });
        } else if (farm.location) {
            const geocoder = new AMap.Geocoder({
                city: '全国',
                radius: 1000
            });
            
            geocoder.getLocation(farm.location, function(status, result) {
                if (status === 'complete' && result.geocodes.length) {
                    const lnglat = result.geocodes[0].location;
                    map.setCenter(lnglat);
                    new AMap.Marker({
                        position: lnglat,
                        map: map,
                        content: '<div class="mini-marker"></div>'
                    });
                }
            });
        }
    } catch (error) {
        console.error('初始化地图失败:', error);
    }
}

            // 显示全屏地图
function showFullMap(farm) {
    const modal = document.getElementById('fullMapModal');
    const mapContainer = document.getElementById('fullMap');
    
    // 显示农场信息
    document.getElementById('mapFarmName').textContent = farm.name;
    document.getElementById('mapFarmAddress').textContent = farm.location;
    
    // 显示模态框
    modal.style.display = 'flex';
    
    // 初始化地图
    currentFullMap = new AMap.Map(mapContainer, {
        zoom: 14,
        viewMode: '3D'
    });
    
    // 地理编码获取坐标
    const geocoder = new AMap.Geocoder();
    geocoder.getLocation(farm.location, function(status, result) {
        if (status === 'complete' && result.geocodes.length) {
            const lnglat = result.geocodes[0].location;
            
            // 设置地图中心点
            currentFullMap.setCenter(lnglat);
            
            // 添加标记
            new AMap.Marker({
                position: lnglat,
                map: currentFullMap,
                title: farm.name
            });
            
            // 添加信息窗口
            const infoWindow = new AMap.InfoWindow({
                content: `<div style="padding:5px;">
                    <h4>${farm.name}</h4>
                    <p>${farm.location}</p>
                    <p>面积: ${farm.area}亩</p>
                </div>`,
                offset: new AMap.Pixel(0, -30)
            });
            
            infoWindow.open(currentFullMap, lnglat);
            
            // 添加缩放控件
            currentFullMap.addControl(new AMap.ControlBar({
                showZoomBar: true,
                showControlButton: true,
                position: {
                    right: '10px',
                    top: '10px'
                }
            }));
            
        } else {
            console.error('地理编码失败:', farm.location, result);
            // 使用默认位置
            currentFullMap.setCenter([116.397428, 39.90923]); // 北京天安门坐标
            alert('无法定位农场位置，已显示默认位置');
        }
    });
}
            // 显示编辑农场模态框
            function showEditFarmModal(farmId) {
                modalTitle.textContent = '编辑农场';
                
                fetch(`${API_BASE_URL}/${farmId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 1) {
                            const farm = data.data;
                            document.getElementById('farmId').value = farm.id;
                            document.getElementById('farmName').value = farm.name;
                            document.getElementById('farmLocation').value = farm.location;
                            document.getElementById('farmArea').value = farm.area;
                            document.getElementById('farmDate').value = farm.establish_date;
                            document.getElementById('farmManager').value = farm.manager_id;
                            document.getElementById('farmStatus').value = farm.status;
                            document.getElementById('farmDescription').value = farm.description || '';
                            farmModal.style.display = 'flex';
                        } else {
                            alert('获取农场详情失败: ' + data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('获取农场详情时出错');
                    });
            }
            
            // 隐藏农场模态框
            function hideFarmModal() {
                farmModal.style.display = 'none';
            }
            
            // 处理农场表单提交
            function handleFarmSubmit(e) {
                e.preventDefault();
                
                const farmId = document.getElementById('farmId').value;
                const isEdit = !!farmId;
                
                const farmData = {
                    name: document.getElementById('farmName').value,
                    location: document.getElementById('farmLocation').value,
                    area: parseFloat(document.getElementById('farmArea').value),
                    establish_date: document.getElementById('farmDate').value,
                    manager_id: document.getElementById('farmManager').value,
                    status: parseInt(document.getElementById('farmStatus').value),
                    description: document.getElementById('farmDescription').value
                };
                
                // 验证数据
                if (!farmData.name || !farmData.location || isNaN(farmData.area)) {
                    alert('请填写完整信息');
                    return;
                }
                
                const saveBtn = farmForm.querySelector('button[type="submit"]');
                const originalText = saveBtn.innerHTML;
                saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
                saveBtn.disabled = true;
                
                const url = isEdit ? `${API_BASE_URL}/${farmId}` : API_BASE_URL;
                const method = isEdit ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(farmData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        alert(isEdit ? '农场更新成功' : '农场添加成功');
                        hideFarmModal();
                        loadFarms();
                    } else {
                        alert((isEdit ? '更新' : '添加') + '农场失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert((isEdit ? '更新' : '添加') + '农场时出错');
                })
                .finally(() => {
                    saveBtn.innerHTML = originalText;
                    saveBtn.disabled = false;
                });
            }
            
            // 确认删除农场
            function confirmDeleteFarm(farmId) {
                if (confirm('确定要删除这个农场吗？此操作不可恢复。')) {
                    deleteFarm(farmId);
                }
            }
            
            // 删除农场
            function deleteFarm(id) {
                showLoading();
                
                fetch(`${API_BASE_URL}/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        alert('农场删除成功');
                        loadFarms();
                    } else {
                        alert('删除农场失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除农场时出错');
                })
                .finally(() => {
                    hideLoading();
                });
            }
            
            // 加载负责人选项
            function loadManagers() {
                fetch(`${BASE_URL}/admin/employee/page`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 1) {
                            const managerSelect = document.getElementById('farmManager');
                            managerSelect.innerHTML = '<option value="">选择负责人</option>';
                            
                            data.data.records.forEach(employee => {
                                const option = document.createElement('option');
                                option.value = employee.id;
                                option.textContent = employee.name;
                                managerSelect.appendChild(option);
                            });
                        } else {
                            console.error('获取员工列表失败:', data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        // 使用模拟数据作为后备
                        const managerSelect = document.getElementById('farmManager');
                        managerSelect.innerHTML = `
                            <option value="">选择负责人</option>
                            <option value="1">管理员</option>
                            <option value="2">张三</option>
                            <option value="4">小明</option>
                            <option value="6">王五</option>
                        `;
                    });
            }
            
            // 设置活动菜单项
            function setActiveMenuItem() {
                const currentPage = window.location.pathname.split('/').pop().replace('.html', '');
                document.querySelectorAll('.sidebar-menu li').forEach(item => {
                    item.classList.remove('active');
                    if (item.getAttribute('data-page') === currentPage) {
                        item.classList.add('active');
                    }
                });
            }
        });
    </script>

    <!-- 在body底部，其他模态框之后添加 -->
<div id="fullMapModal">
    <div class="full-map-container">
        <button class="close-full-map" id="closeFullMapBtn">&times;</button>
        <div id="fullMap"></div>
        <div class="map-info">
            <h3 id="mapFarmName"></h3>
            <p id="mapFarmAddress"></p>
        </div>
    </div>
</div>

</body>
</html>